package com.fadadianqi.logistics.admin.net.mina;

import com.fadadianqi.logistics.admin.net.*;
import org.apache.mina.core.session.IoSession;

public class ClientSession implements Session {

    private Connection connection;

    private IoSession ioSession;

    private String id;

    public ClientSession(IoSession session) {
        this.id = java.util.UUID.randomUUID().toString();
        if (session != null) {
            this.connection = (Connection) session.getAttribute(SessionAttrName.CONNECTION);
            this.ioSession = session;
            this.ioSession.setAttribute(SessionAttrName.ID, id);
        }
    }

    @Override
    public String getId() {
        return id;
    }

    @Override
    public int getStatus() {
        Integer i = (Integer) ioSession.getAttribute(SessionAttrName.STATUS);
        if (i != null) {
            return i;
        } else {
            return -1;
        }
    }

    @Override
    public void close() {
        if (ioSession != null) {
            ioSession.close(Boolean.TRUE);
        }
        if (connection != null && !connection.isClosed()) {
            connection.close();
        }
        SessionManager.delSession(this);
    }

    @Override
    public boolean isClosed() {
        return connection == null || connection.isClosed();
    }

    @Override
    public void process(Packet packet) {
        connection.deliver(packet);
    }

    @Override
    public void setAttribute(Object key, Object value) {
        ioSession.setAttribute(key, value);
    }

    @Override
    public Object getAttribute(Object key) {
        return ioSession.getAttribute(key, null);
    }

}
